import tkinter as tk
from tkinter import filedialog, messagebox
from PyPDF2 import PdfReader, PdfWriter
import copy
import os

def crop_page(page, is_first_half=True, vertical_split=False):
    """
    裁剪页面为A4大小
    
    参数:
    page: PDF页面对象
    is_first_half: True表示保留第一半（左半或上半），False表示保留第二半（右半或下半）
    vertical_split: True表示上下切割，False表示左右切割
    返回: 裁剪后的页面
    """
    # 创建新的页面对象
    new_page = copy.deepcopy(page)
    
    # 获取原始页面尺寸
    original_width = float(page.mediabox.width)
    original_height = float(page.mediabox.height)
    
    # 根据切割方向设置裁剪区域
    if vertical_split:
        # 上下切割
        if is_first_half:
            new_page.mediabox.upper_right = (original_width, original_height)
            new_page.mediabox.lower_left = (0, original_height/2)
        else:
            new_page.mediabox.upper_right = (original_width, original_height/2)
            new_page.mediabox.lower_left = (0, 0)
    else:
        # 左右切割
        if is_first_half:
            new_page.mediabox.upper_right = (original_width/2, original_height)
            new_page.mediabox.lower_left = (0, 0)
        else:
            new_page.mediabox.upper_right = (original_width, original_height)
            new_page.mediabox.lower_left = (original_width/2, 0)
    
    return new_page

def split_and_reorder_pdf(input_path):
    """修改后的分割函数，返回输出路径和执行结果"""
    try:
        # 生成输出文件路径
        file_dir = os.path.dirname(input_path)
        file_name = os.path.splitext(os.path.basename(input_path))[0]
        output_path = os.path.join(file_dir, f"{file_name}_output.pdf")

        # 创建PDF读取器和写入器
        reader = PdfReader(input_path)
        writer = PdfWriter()

        # 获取A3页数并计算总页数
        total_a3_pages = len(reader.pages)
        total_pages = total_a3_pages * 2

        # 创建临时存储，用于保存分割后的页面
        pages_dict = {}

        # 检查第一页的方向来决定切割方式
        first_page = reader.pages[0]
        original_width = float(first_page.mediabox.width)
        original_height = float(first_page.mediabox.height)
        vertical_split = original_width < original_height
        
        print(f"页面尺寸: 宽度={original_width}, 高度={original_height}")
        print(f"使用{'上下' if vertical_split else '左右'}切割方式")

        # 处理每个A3页面
        for a3_index in range(total_a3_pages):
            original_page = reader.pages[a3_index]
            
            # 计算页码对
            if a3_index % 2 == 0:
                front_page_num = total_pages - a3_index
                back_page_num = a3_index + 1
            else:
                front_page_num = a3_index + 1
                back_page_num = total_pages - a3_index

            # 分割A3页面为两个A4页面
            first_half = crop_page(original_page, is_first_half=True, vertical_split=vertical_split)
            second_half = crop_page(original_page, is_first_half=False, vertical_split=vertical_split)

            # 存储分割后的页面
            pages_dict[front_page_num] = first_half
            pages_dict[back_page_num] = second_half

            print(f"处理A3页面 {a3_index + 1}: 分割为A4页面 {front_page_num} 和 {back_page_num}")

        # 按页码顺序添加页面到最终文档
        for page_num in range(1, total_pages + 1):
            writer.add_page(pages_dict[page_num])

        # 保存最终文档
        with open(output_path, 'wb') as output_file:
            writer.write(output_file)
        
        return output_path, True, "PDF处理完成！"

    except Exception as e:
        return None, False, f"处理PDF时出错: {str(e)}"

class PDFSplitterApp:
    def __init__(self, root):
        self.root = root
        self.root.title("PDF分割工具")
        self.root.geometry("500x200")
        
        # 创建主框架
        main_frame = tk.Frame(root, padx=20, pady=20)
        main_frame.pack(expand=True, fill='both')

        # 文件选择框和按钮
        self.file_frame = tk.Frame(main_frame)
        self.file_frame.pack(fill='x', pady=(0, 20))

        self.file_path = tk.StringVar()
        self.file_entry = tk.Entry(self.file_frame, textvariable=self.file_path, width=50)
        self.file_entry.pack(side='left', padx=(0, 10))

        self.browse_button = tk.Button(self.file_frame, text="选择文件", command=self.browse_file)
        self.browse_button.pack(side='left')

        # 执行按钮
        self.process_button = tk.Button(main_frame, text="开始处理", command=self.process_pdf)
        self.process_button.pack()

        # 状态标签
        self.status_label = tk.Label(main_frame, text="", wraplength=460)
        self.status_label.pack(pady=(20, 0))

    def browse_file(self):
        """打开文件选择对话框"""
        file_path = filedialog.askopenfilename(
            filetypes=[("PDF files", "*.pdf"), ("All files", "*.*")]
        )
        if file_path:
            self.file_path.set(file_path)

    def process_pdf(self):
        """处理PDF文件"""
        input_path = self.file_path.get()
        if not input_path:
            messagebox.showwarning("警告", "请先选择PDF文件！")
            return

        # 禁用按钮，防止重复点击
        self.process_button.config(state='disabled')
        self.status_label.config(text="正在处理...")
        self.root.update()

        try:
            output_path, success, message = split_and_reorder_pdf(input_path)
            
            if success:
                self.status_label.config(
                    text=f"处理成功！\n输出文件：{output_path}",
                    fg="green"
                )
                messagebox.showinfo("成功", f"PDF处理完成！\n输出文件：{output_path}")
            else:
                self.status_label.config(
                    text=f"处理失败：{message}",
                    fg="red"
                )
                messagebox.showerror("错误", message)

        except Exception as e:
            self.status_label.config(
                text=f"发生错误：{str(e)}",
                fg="red"
            )
            messagebox.showerror("错误", str(e))

        finally:
            # 重新启用按钮
            self.process_button.config(state='normal')

def main():
    root = tk.Tk()
    app = PDFSplitterApp(root)
    root.mainloop()

if __name__ == "__main__":
    main()